<template>
  <div class="user-center">
    <el-row :gutter="20">
      <!-- 用户信息卡片 -->
      <el-col :xs="24" :sm="8">
        <el-card class="user-card">
          <div class="user-avatar">
            <el-avatar :size="100" icon="el-icon-user-solid"></el-avatar>
          </div>
          <div class="user-info">
            <h2>{{ user.username }}</h2>
            <p v-if="user.email"><i class="el-icon-message"></i> {{ user.email || '未设置邮箱' }}</p>
            <p v-if="user.phone"><i class="el-icon-phone"></i> {{ user.phone || '未设置手机号' }}</p>
            <p v-if="user.address"><i class="el-icon-location"></i> {{ user.address || '未设置地址' }}</p>
          </div>
          <div class="user-actions">
            <el-button type="primary" @click="showEditDialog">编辑资料</el-button>
          </div>
        </el-card>
        
        <!-- 消息通知 -->
        <el-card class="message-card">
          <div slot="header" class="card-header">
            <span>我的消息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="fetchMessages">刷新</el-button>
          </div>
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          <div v-else-if="messages.length === 0" class="empty-data">
            暂无消息
          </div>
          <div v-else class="message-list">
            <div v-for="(item, index) in messages" :key="index" 
                 class="message-item" 
                 :class="{ 'unread': item.readStatus === 0 }"
                 @click="readMessage(item)">
              <div class="message-title">{{ item.title }}</div>
              <div class="message-content">{{ item.content }}</div>
              <div class="message-time">{{ formatDate(item.createTime) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
        
        <el-card class="recent-orders">
          <div slot="header" class="card-header">
            <span>最近订单</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="viewOrders('all')">查看全部</el-button>
          </div>
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          <div v-else-if="recentOrders.length === 0" class="empty-data">
            暂无订单
          </div>
          <el-table v-else :data="recentOrders" style="width: 100%">
            <el-table-column prop="orderNo" label="订单编号" width="180"></el-table-column>
            <el-table-column label="服务类型">
              <template slot-scope="scope">
                {{ scope.row.serviceTypeName || '未知服务' }}
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                ¥{{ scope.row.totalAmount }}
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewOrderDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        
        <el-card class="quick-actions">
          <div slot="header" class="card-header">
            <span>快捷操作</span>
          </div>
          <el-row :gutter="20">
            <el-col :xs="12" :sm="8" :md="6">
              <div class="action-card" @click="$router.push('/user/order/create')">
                <i class="el-icon-plus"></i>
                <span>新建订单</span>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="6">
              <div class="action-card" @click="$router.push('/user/promotions')">
                <i class="el-icon-medal"></i>
                <span>优惠活动</span>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="6">
              <div class="action-card" @click="$router.push('/user/order/list')">
                <i class="el-icon-s-order"></i>
                <span>全部订单</span>
              </div>
            </el-col>
            <el-col :xs="12" :sm="8" :md="6">
              <div class="action-card" @click="logout">
                <i class="el-icon-switch-button"></i>
                <span>退出登录</span>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 编辑资料对话框 -->
    <el-dialog title="编辑个人资料" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { formatDate } from '@/utils/date'

export default {
  name: 'UserCenter',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      orderStats: {
        all: 0,
        pending: 0,
        processing: 0,
        completed: 0
      },
      recentOrders: [],
      messages: [],
      loading: false,
      editDialogVisible: false,
      editForm: {
        username: '',
        email: '',
        phone: '',
        address: ''
      },
      editRules: {
        email: [
          { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchUserInfo()
    this.fetchOrderStats()
    this.fetchRecentOrders()
    this.fetchMessages()
  },
  methods: {
    formatDate,
    async fetchUserInfo() {
      try {
        const userId = this.user.id
        if (!userId) return
        
        try {
          const res = await axios.get(`/api/user/info?userId=${userId}`).then(res => res.data)
          if (res.code === 200) {
            this.user = res.data
            localStorage.setItem('user', JSON.stringify(res.data))
          }
        } catch (error) {
          console.error('获取用户信息失败', error)
          // 不做任何处理，继续使用localStorage中的用户信息
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
      }
    },
    async fetchOrderStats() {
      try {
        const userId = this.user.id
        if (!userId) return
      } catch (error) {
        console.error('获取订单统计失败', error)
        // 模拟数据
        this.orderStats = {
          all: 5,
          pending: 1,
          processing: 2,
          completed: 2
        }
      }
    },
    async fetchRecentOrders() {
      this.loading = true
      try {
        const userId = this.user.id
        if (!userId) return
        
        try {
          const res = await axios.get(`/api/order/list?userId=${userId}`).then(res => res.data)
          if (res.code === 200) {
            this.recentOrders = res.data.slice(0, 5) // 只显示最近5条
          }
        } catch (error) {
          console.error('获取最近订单失败', error)
          // 使用模拟数据
          this.recentOrders = this.getMockOrders(userId)
        }
      } catch (error) {
        console.error('获取最近订单失败', error)
      } finally {
        this.loading = false
      }
    },
    getMockOrders(userId) {
      // 生成模拟订单数据
      const mockOrders = []
      for (let i = 1; i <= 5; i++) {
        const status = i % 5 // 0-4 状态循环
        const date = new Date()
        date.setDate(date.getDate() - i) // 每个订单日期往前推i天
        
        mockOrders.push({
          id: i,
          orderNo: `ORD${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}${String(i).padStart(4, '0')}`,
          userId: userId,
          serviceTypeId: i % 3 + 1,
          serviceTypeName: i % 3 === 0 ? '标准洗涤' : (i % 3 === 1 ? '高级洗护' : '快速洗衣'),
          clothesTypeId: i % 4 + 1,
          clothesTypeName: ['T恤', '衬衫', '裤子', '外套'][i % 4],
          quantity: Math.floor(Math.random() * 5) + 1,
          totalAmount: ((Math.floor(Math.random() * 10) + 1) * 10).toFixed(2),
          status: status,
          createTime: date.toISOString(),
          updateTime: date.toISOString()
        })
      }
      return mockOrders
    },
    async fetchMessages() {
      this.loading = true
      try {
        const userId = this.user.id
        if (!userId) return
        
        const res = await axios.get(`/api/message/list?userId=${userId}`).then(res => res.data)
        if (res.code === 200) {
          this.messages = res.data
        }
      } catch (error) {
        console.error('获取消息列表失败', error)
      } finally {
        this.loading = false
      }
    },
    async readMessage(message) {
      if (message.readStatus === 0) {
        try {
          await axios.put(`/api/message/read/${message.id}`).then(res => res.data)
          message.readStatus = 1
          this.fetchMessages()
        } catch (error) {
          console.error('标记消息已读失败', error)
        }
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付待取件',
        2: '已取件处理中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'primary',
        3: 'success',
        4: 'info'
      }
      return typeMap[status] || ''
    },
    viewOrderDetail(order) {
      this.$router.push(`/user/order/detail?orderNo=${order.orderNo}`)
    },
    viewOrders(type) {
      let query = {}
      
      if (type === 'pending') {
        query.status = 1
      } else if (type === 'processing') {
        query.status = 2
      } else if (type === 'completed') {
        query.status = 3
      }
      
      this.$router.push({
        path: '/user/order/list',
        query
      })
    },
    showEditDialog() {
      this.editForm = {
        username: this.user.username,
        email: this.user.email || '',
        phone: this.user.phone || '',
        address: this.user.address || ''
      }
      this.editDialogVisible = true
    },
    submitEditForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              id: this.user.id,
              username: this.editForm.username,
              email: this.editForm.email,
              phone: this.editForm.phone,
              address: this.editForm.address
            }
            
            const res = await axios.put('/api/user/update', params).then(res => res.data)
            if (res.code === 200) {
              this.$message.success('个人资料已更新')
              this.editDialogVisible = false
              this.fetchUserInfo()
            } else {
              this.$message.error(res.message || '更新失败')
            }
          } catch (error) {
            console.error('更新个人资料失败', error)
            this.$message.error('更新个人资料失败')
          }
        }
      })
    },
    logout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        localStorage.removeItem('userId')
        this.$router.push('/login')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.user-center {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.user-card {
  text-align: center;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-avatar {
  margin: 20px 0;
}

.user-info {
  margin-bottom: 20px;
}

.user-info h2 {
  margin-bottom: 15px;
  color: #303133;
}

.user-info p {
  margin: 8px 0;
  color: #606266;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-info p i {
  margin-right: 5px;
}

.user-actions {
  margin-bottom: 20px;
}

.message-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
}

.message-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f9f9f9;
}

.message-item.unread {
  background-color: #ecf5ff;
}

.message-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.message-content {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-time {
  color: #909399;
  font-size: 12px;
  text-align: right;
}

.order-stats {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-row {
  padding: 10px 0;
}

.stat-item {
  text-align: center;
  cursor: pointer;
  padding: 15px 0;
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-5px);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  margin-top: 5px;
  color: #606266;
}

.recent-orders {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.quick-actions {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-card {
  background-color: #fff;
  height: 80px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px 0 rgba(0, 0, 0, 0.1);
  border-color: #409EFF;
}

.action-card i {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 8px;
}

.loading-container {
  padding: 20px 0;
}

.empty-data {
  padding: 30px 0;
  text-align: center;
  color: #909399;
}

@media (max-width: 768px) {
  .user-center {
    padding: 10px;
  }
  
  .stat-item {
    padding: 10px 0;
  }
}
</style>